package com.mtzqc.common.kt

import android.os.SystemClock
import android.view.View
import android.view.ViewTreeObserver
import com.mtzqc.common.R

/**
 * @copyright: 2019-2021,重庆菜鸽途讯科技有限公司
 * @author: czw
 * @date: 2021/6/15 10:03
 * @description:
 */

fun filterListener(
    wait: Long = 300,
    block: ((View) -> Unit),
    filter: ((View) -> Boolean) = { true }
): View.OnClickListener {
    return View.OnClickListener { v ->
        val current = SystemClock.elapsedRealtime()
        val ts = (v.getTag(R.id.common_click_lock_ts) as? Long) ?: 0L
        if (current - ts > wait) {
            v.setTag(R.id.common_click_lock_ts, current)
            if (filter.invoke(v)) {
                block(v)
            }
        }
    }
}

fun View.onClick(wait: Long = 300, block: ((View) -> Unit)): View.OnClickListener {
    return filterListener(wait, block).also { setOnClickListener(it) }
}

fun <T : View> T.isShow(): Boolean {
    return View.VISIBLE == this.visibility
}

fun <T : View> T.hide(gone: Boolean = true): T {
    var result = if (gone) View.GONE else View.INVISIBLE
    if (result != this.visibility) {
        this.visibility = result
    }
    return this
}

fun <T : View> T.show(): T {
    if (!isShow()) {
        this.visibility = View.VISIBLE
    }
    return this
}

fun <T : View> T.afterLayout(block: T.(Int, Int) -> Unit): ViewTreeObserver.OnGlobalLayoutListener {
    val layoutListener = object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            if (width > 0 || height > 0) {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                block(width, height)
            }
        }
    }
    viewTreeObserver.addOnGlobalLayoutListener(layoutListener)
    return layoutListener
}

